<template>
  <div>
    <div id="reactCode" class="h-20rem"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import loader from "@monaco-editor/loader";
import * as monaco from 'monaco-editor';

const reactCode = ref(`
import React, { useEffect, useState } from "react";

function App() {
    const [num, setNum] = useState(() => {
        const num1 = 1 + 2;
        const num2 = 2 + 3;
        return num1 + num2
    });

    return (
      <button style={{margin: 100}} onClick={() => setNum((prevNum) => prevNum + 1)}>{num}</button>
    );
}

export default App;
`)

const codeInit = async (selector: string): Promise<monaco.editor.IStandaloneCodeEditor | undefined> => {
  const el = document.querySelector(selector) as HTMLElement
  let editor
  if (el) {
    loader.config({
      monaco
    })
    const monacoIns = await loader.init()
    editor = monacoIns.editor.create(el, {
      value: reactCode.value,
      language: "typescript",
      theme: 'vs-dark', // 官方自带三种主题vs, hc-black, or vs-dark
      overviewRulerBorder: false, // 滚动是否有边框
      automaticLayout: true, // 自动布局
      readOnly: false, // 是否只读
      minimap: { // 关闭代码缩略图
        enabled: false // 是否启用预览图
      },
      lineNumbers: 'on', // 控制行号的显隐
      scrollBeyondLastLine: false, // 禁用额外滚动区
      scrollbar: {
        verticalScrollbarSize: 4, // 垂直滚动条宽度，默认px
        horizontalScrollbarSize: 4 // 水平滚动条高度
      },
    });
    return editor
  }
}

onMounted(async () => {
  const editor = await codeInit("#reactCode")
  editor?.onDidChangeModelContent((e) => {
    reactCode.value = editor?.getValue()
  })
})



defineExpose({ reactCode })
</script>

<style scoped>
</style>
